<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>信息提交表单</title>
  <style>
    * { box-sizing: border-box; }
    body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      background-color: #f4f6f8;
      margin: 0;
      padding: 40px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    textarea {
      width: 100%;
      padding: 10px;
      border-radius: 8px;
      border: 1px solid #ccc;
      font-family: inherit;
      font-size: 14px;
      transition: border-color 0.3s;
      resize: vertical; /* 允许垂直拖动 */
      box-sizing: border-box;
    }

    textarea:focus {
      border-color: #007bff;
      outline: none;
    }
    .card {
      background-color: #fff;
      padding: 24px;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      width: 100%;
      max-width: 60%;
      margin-bottom: 30px;
    }
    h2 {
      margin-top: 0;
      margin-bottom: 20px;
      text-align: center;
      color: #333;
    }
    .form-group {
      margin-bottom: 16px;
    }
    label {
      display: block;
      margin-bottom: 6px;
      font-weight: bold;
      color: #555;
    }
    input[type="text"],
    input[type="password"] {
      width: 100%;
      padding: 10px;
      border-radius: 8px;
      border: 1px solid #ccc;
      transition: border-color 0.3s;
    }
    input:focus {
      border-color: #007bff;
      outline: none;
    }
    button {
      width: 100%;
      padding: 10px;
      background-color: #007bff;
      color: white;
      font-size: 16px;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    button:hover {
      background-color: #0056b3;
    }
    #nameList {
      width: 100%;
      max-width: 400px;
    }
    .name-item {
      background-color: #ffffff;
      padding: 12px 16px;
      margin-bottom: 10px;
      border-left: 5px solid #007bff;
      border-radius: 6px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.05);
      color: #333;
    }
  </style>
</head>
<body>

  <div class="card">
    <h2>提交信息</h2>
    <form id="infoForm">
      <div class="form-group">
        <label for="name">名字</label>
        <input type="text" id="name" required>
      </div>
      <div class="form-group">
        <label for="content">内容</label>
        <textarea id="content" rows="3" style="resize: vertical; width: 100%;" required></textarea>
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input type="password" id="password" required>
      </div>
      <button type="submit">提交</button>
    </form>
  </div>

  <div id="nameList">
    <h2>已提交的名字</h2>
    <div id="namesContainer"></div>
  </div>

  <script>
    const form = document.getElementById('infoForm');
    const nameInput = document.getElementById('name');
    const contentInput = document.getElementById('content');
    const passwordInput = document.getElementById('password');
    const namesContainer = document.getElementById('namesContainer');
    passwordInput.onblur=()=>{
      getList(passwordInput.value.trim())
    }
    const nameSet = new Set();

    form.addEventListener('submit', function (e) {
      e.preventDefault();
      const name = nameInput.value.trim();
      const content = contentInput.value.trim();
      const password = passwordInput.value;

      if (name && !nameSet.has(name)) {
        nameSet.add(name);
        // const div = document.createElement('div');
        // div.className = 'name-item';
        // div.textContent = name;
        // namesContainer.appendChild(div);
      }

      // 发送请求
      create(name, content, password);
    //   form.reset();
    });

    function getList(pwd){
      if(!pwd) return
      httpRequest("Get","http://lsz75.top:8090/general/content/key/list",null,pwd,(err,succ)=>{
        if(err){
          console.log(`获取列表错误`,err);
        }else{
          console.log(`success`,succ);
          const arr = JSON.parse(succ.data)
          document.querySelectorAll('.name-item').forEach(function(el) {
              el.remove();
          });
          setTimeout(()=>{
            arr.forEach(item=>{
              console.log(`遍历`,);
            const div = document.createElement('div');
            div.className = 'name-item';
            div.textContent = item;
            namesContainer.appendChild(div);
          })
          },200)
        }
      })
    }

    function create(name, content, password) {
      httpRequest("POST", "http://lsz75.top:8090/general/create/content/touch", {
        key: name,
        content: content
      },password, (err, succ) => {
        if (err) {
          alert(err);
        } else {
          if (succ.code == 200) {
            alert("成功！");
          } else {
            alert("失败！");
          }
        }
      });
    }

    function httpRequest(method, url, data, pwd, callback) {
    const xhr = new XMLHttpRequest();
    
    // 添加 withCredentials 支持跨域带凭证的请求
    // xhr.withCredentials = true;
    
    xhr.open(method.toUpperCase(), url, true);
    
    // 设置安全头部
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    // 仅在密码存在时添加头部
    if (pwd && typeof pwd === 'string') {
      xhr.setRequestHeader('password', pwd); // 使用自定义头部前缀避免冲突
    }

    // 错误处理增强
    xhr.onerror = function() {
      callback(new Error('网络错误，请求无法发送'));
    };

    // 超时处理（可选）
    xhr.timeout = 10000; // 10秒超时
    xhr.ontimeout = function() {
      callback(new Error('请求超时'));
    };

    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        try {
          if (xhr.status >= 200 && xhr.status < 300) {
            // 处理空响应
            const response = xhr.responseText ? JSON.parse(xhr.responseText) : null;
            callback(null, response);
          } else {
            // 尝试解析错误响应
            let errorMsg = `请求失败，状态码：${xhr.status}`;
            try {
              const errorResponse = xhr.responseText ? JSON.parse(xhr.responseText) : {};
              if (errorResponse.message) errorMsg += ` - ${errorResponse.message}`;
            } catch (e) {}
            callback(new Error(errorMsg));
          }
        } catch (parseError) {
          callback(new Error(`响应解析失败: ${parseError.message}`));
        }
      }
    };

    // 安全地处理数据发送
    try {
      const payload = data ? JSON.stringify(data) : null;
      xhr.send(payload);
    } catch (sendError) {
      callback(new Error(`请求发送失败: ${sendError.message}`));
    }
  }
  </script>

</body>
</html>
